package com.towa.ninemanmorris;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.provider.Settings.Secure;
import android.util.Log;

public class NineManMorrisC2DMRegistrationReceiver extends BroadcastReceiver {

	private Sender sender;
	private Receiver receiver;

	@Override
	public void onReceive(Context context, Intent intent) {
		String action = intent.getAction();
		Log.w("C2DM", "Registration Receiver called");
		if ("com.google.android.c2dm.intent.REGISTRATION".equals(action)) {
			Log.w("C2DM", "Received registration ID");
			final String registrationId = intent
					.getStringExtra("registration_id");
			String error = intent.getStringExtra("error");
			Log.d("C2DM", "dmControl: registrationId = " + registrationId
					+ ", error = " + error);
			String deviceId = Secure.getString(context.getContentResolver(),
					Secure.ANDROID_ID);
			// createNotification(context, registrationId);
			sender = new Sender();
			sender.doInBackground("registration::" + registrationId + " " + deviceId);
//			sender.doInBackground(registrationId, deviceId);
//			 sendRegistrationIdToServer(deviceId, registrationId);
			// Also save it in the preference to be able to show it later
			 saveRegistrationId(context, registrationId, deviceId);
		} else if (action.equals("com.google.android.c2dm.intent.RECEIVE")) {
			Log.i("C2DM", "Recieved something!");
			String payload = intent.getExtras().getString("group");
//			receiver = new Receiver();
//			String received = receiver.doInBackground();
			Log.d("C2DM", "payload: " + payload);
			if (payload != null) {
				HighscoreWrapper hsw = new ReceivedTasker().doInBackground(payload);
				HighscoreDB hDB = new HighscoreDB(context);
				hDB.open();
				hDB.addOrUpdateHighscore(hsw);
				hDB.close();
			}
		}
	}
	
	private void savePayloadInSharedPreferences(Context context, String payload) {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
		Editor edt = prefs.edit();
		edt.putString("payload", payload);
		edt.commit();
	}

	private void saveRegistrationId(Context context, String registrationId, String deviceId) {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
		Editor edit = prefs.edit();
		edit.putString("authentication", registrationId);
		edit.putString("deviceId", deviceId);
		edit.commit();
	}

	class Receiver extends AsyncTask<Void, Void, String> {

		private Socket socket;
		private BufferedReader br;
		
		@Override
		protected void onPreExecute() {
			
		}
		
		@Override
		protected String doInBackground(Void... inputs) {
			String string = "";
			try {
				if (socket == null) {
					socket = new Socket(NineManMorrisConstants.INET_ADDRESS, NineManMorrisConstants.INET_PORT);
				}
			} catch (UnknownHostException e) {
				Log.e("C2DM", e.toString());
			} catch (IOException e) {
				Log.e("C2DM", e.toString());
			}
			try {
				br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
				string = br.readLine();
			} catch (IOException e) {
				Log.e("C2DM", e.toString());
			}
			return string;
		}
		
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			try {
				if (socket != null) {
					socket.close();
				}
				if (br != null) {
					br.close();
				}
			} catch (IOException e) {
				Log.e("C2DM", e.toString());
			}
		}
		
	}
	
	class Sender extends AsyncTask<String, Void, Void> {
		
		private Socket socket;
		private BufferedReader br;
		private PrintWriter pw;
		
		@Override
		protected void onPreExecute() {
			
		}

		@Override
		protected Void doInBackground(String... inputs) {
//			sendRegistrationIdToServer(inputs[0], inputs[1]);
			try {
				try {
//					if (socket == null) {
					socket = new Socket(NineManMorrisConstants.INET_ADDRESS, NineManMorrisConstants.INET_PORT);
//					}
				} catch (UnknownHostException e) {
					Log.e("C2DM", e.toString());
				} catch (IOException e) {
					Log.e("C2DM", e.toString());
				}
				if (socket != null) {
					pw = new PrintWriter(socket.getOutputStream());
					pw.println(inputs[0]);
					pw.flush();
				} else {
					Log.e("C2DM", "Socket: " + socket);
				}
			} catch (IOException e) {
				Log.e("C2DM", e.toString());
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					Log.e("C2DM", e.toString());
				}
			}
			if (pw != null) {
				pw.close();
			}
			try {
				if (socket != null) {
					socket.close();
				}
			} catch (IOException e) {
				Log.e("C2DM", e.toString());
			}
		}

	}

	public void sendRegistrationIdToServer(String deviceId,
			String registrationId) {

		Log.d("C2DM", "Sending registration ID to my application server");
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost("http://vogellac2dm.appspot.com/register");
		try {
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
			// Get the deviceID
			nameValuePairs.add(new BasicNameValuePair("deviceid", deviceId));
			nameValuePairs.add(new BasicNameValuePair("registrationid",
					registrationId));

			post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			Log.i("C2DM", post.toString());
			HttpResponse response = client.execute(post);
			BufferedReader rd = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent()));
			String line = "";
			while ((line = rd.readLine()) != null) {
				Log.e("HttpResponse", line);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
